<template>
  <div class="version-wrap">
   <Info @latestNpmVersion="getLatestNpm"></Info>
    <template v-if="showModal">
      <Update :gitLoading="gitLoading" :latestNpmDescription="latestNpmDescription" @updateGit="updateGitRemote" @updateNpm="updateNpmPackage"  @hideUpdate="showUpdate(false)"></Update>
    </template>
    <a-form class="version-btns">
      <a-form-item >
        <a-button type="primary" @click="showUpdate(true)">更新</a-button>
      </a-form-item>
    </a-form>

  </div>
</template>

<script setup>
import {nextTick, ref} from "vue";

import Info from './components/info.vue'
import Update from './components/update.vue'
import {storage} from "../../utils/storage";
import {getNextVersion} from "../../utils/version";
import {publishNpm, updateGit, updateNpm} from "../../api/api";
import {message} from "ant-design-vue";

// 当前显示的组件
let currentComponent = ref('')
const latestNpmDescription = ref('')
// 是否显示弹框
const showModal = ref(false)
// git按钮相关操作
const showUpdate = async (status)=>{
  showModal.value = status
}
const updateNpmPackage = async (description)=>{
  const newVersion = getNextVersion(storage.session.get('version'))
  const res = await updateNpm({version:newVersion,description})
  if(res.type === 'success'){
    message.success('package.json包更新成功')
    await  updateGitRemote('update-version',getNextVersion(storage.session.get('version')))
    const res =  publishNpm({dir:'functions'})
    msgInfo(res)
  }

}
const gitLoading = ref(false)
const updateGitRemote = async (commit,version)=>{
  gitLoading.value = true
  commit = commit.replace(' ','')
  version = version || storage.session.get('version')
  const commitInfo =  commit + '--version' + version
  console.log({commit: commitInfo})
  const res = await updateGit({commit: commitInfo})
  gitLoading.value = false
  for (let i in res){
    msgInfo(res[i])
  }
  showUpdate(false)
}
const getLatestNpm = (version)=>{
  latestNpmDescription.value = version.description
}
const msgInfo = (res)=>{
  const types = ['error','success']
  const type = types[res.code]
  // message[type](type +' to run：' + res.cmd  )
  if(res.msg){
    message[type](res.msg)
  }
}
</script>

<style scoped>
.version-wrap{
  width: 80%;
  min-width: 1000px;
  margin: 0 auto;
  padding-top: 20px;
}
.version-btns{
  display: flex;
  width: 50%;
  margin: 40px auto;
  justify-content: space-around;
}
</style>
